package com.example.newsapp.view.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.newsapp.R;
import com.example.newsapp.view.activity.ChangePasswordActivity;
import com.example.newsapp.view.activity.LoginActivity;
import com.example.newsapp.viewmodel.ProfileViewModel;

public class ProfileFragment extends Fragment {
    private ProfileViewModel viewModel;
    private TextView textViewUsername;
    private TextView textViewEmail;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        viewModel = new ViewModelProvider(this).get(ProfileViewModel.class);

        textViewUsername = view.findViewById(R.id.textViewUsername);
        textViewEmail = view.findViewById(R.id.textViewEmail);
        Button buttonChangePassword = view.findViewById(R.id.buttonChangePassword);
        Button buttonLogout = view.findViewById(R.id.buttonLogout);

        // 修改密码
        buttonChangePassword.setOnClickListener(v -> {
            startActivity(new Intent(getContext(), ChangePasswordActivity.class));
        });

        // 退出登录
        buttonLogout.setOnClickListener(v -> {
            new AlertDialog.Builder(requireContext())
                    .setTitle("退出登录")
                    .setMessage("确定要退出登录吗？")
                    .setPositiveButton("确定", (dialog, which) -> {
                        viewModel.logout();
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });

        // 观察用户数据
        viewModel.getCurrentUser().observe(getViewLifecycleOwner(), user -> {
            if (user != null) {
                textViewUsername.setText(user.getUsername());
                textViewEmail.setText(user.getEmail());
            }
        });

        // 观察退出登录结果
        viewModel.getLogoutResult().observe(getViewLifecycleOwner(), result -> {
            if (result) {
                Intent intent = new Intent(getContext(), LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            }
        });

        // 加载用户信息
        viewModel.loadUserInfo();
    }
}